FROM node:20-alpine AS base
ARG PORT=7300

FROM base AS dependencies
ENV NODE_ENV=production
WORKDIR /app
COPY package.json yarn.lock ./
RUN yarn cache clean
RUN yarn install --frozen-lockfile

FROM base AS builder
ENV NODE_ENV=development
WORKDIR /app
COPY . .
COPY --chown=node --from=dependencies /app/node_modules ./node_modules

RUN yarn build:prod
RUN yarn cache clean

FROM base AS production
ENV PORT=${PORT}
COPY --chown=node --from=builder /app/next.config.js ./
COPY --chown=node --from=builder /app/public ./public
COPY --chown=node --from=builder /app/.next ./.next
COPY --chown=node --from=builder /app/yarn.lock /app/package.json ./
COPY --chown=node --from=builder /app/.env.production ./.env.production
COPY --chown=node --from=builder /app/next-sitemap.config.js ./next-sitemap.config.js
COPY --chown=node --from=dependencies /app/node_modules ./node_modules
USER node

RUN rm -rf /usr/local/share/.cache

EXPOSE ${PORT}
CMD [ "yarn", "start" ]
